package com.biboheart.demos.random.executor;

import com.biboheart.brick.utils.StringUtils;
import org.springframework.stereotype.Component;

@Component
public class Idcard implements IdentityGenerator{
    private static final String[] cityCode = { "11", "12", "13", "14", "15", "21",
            "22", "23", "31", "32", "33", "34", "35", "36", "37", "41", "42",
            "43", "44", "45", "46", "50", "51", "52", "53", "54", "61", "62",
            "63", "64", "65", "71", "81", "82", "91" };

    /**
     * 每位加权因子
     */
    private static final int[] power = { 7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2 };

    /**
     * 校验位
     */
    private static final String[] parity = {"1", "0", "X", "9", "8", "7", "6", "5", "4", "3", "2"};

    @Override
    public String generate() {
        return getRandomIdcard();
    }

    private String getRandomIdcard() {
        // 随机生成一个地区码(2)
        int index = (int) (Math.random() * cityCode.length);
        String city = cityCode[index];
        // 随机生成4位数字(4)
        int number = (int) (Math.random() * 10000);
        String numberStr = StringUtils.fillZeroFront(String.valueOf(number), 4);
        // 随机生成一个生日(8)
        int year = (int) (Math.random() * 100) + 1900;
        int month = (int) (Math.random() * 12) + 1;
        int day = (int) (Math.random() * 28) + 1;
        String birthday = StringUtils.fillZeroFront(String.valueOf(year), 4) + StringUtils.fillZeroFront(String.valueOf(month), 2) + StringUtils.fillZeroFront(String.valueOf(day), 2);
        // 随机生成一个顺序码(3)
        int order = (int) (Math.random() * 1000);
        String orderStr = StringUtils.fillZeroFront(String.valueOf(order), 3);
        // 组装前17位
        String idcard = city + numberStr + birthday + orderStr;
        // 生成校验码(1)
        char[] c = idcard.toCharArray();
        int[] bit = convertCharToInt(c);
        int sum17 = getPowerSum(bit);
        // 将和值与11取模得到余数进行校验码判断
        String checkCode = parity[sum17 % 11];
        idcard += checkCode;
        return idcard;
    }

    private int[] convertCharToInt(char[] c) throws NumberFormatException {
        int[] a = new int[c.length];
        int k = 0;
        for (char temp : c) {
            a[k++] = Integer.parseInt(String.valueOf(temp));
        }
        return a;
    }

    private static int getPowerSum(int[] bit) {
        int sum = 0;
        if (power.length != bit.length) {
            return sum;
        }
        for (int i = 0; i < bit.length; i++) {
            for (int j = 0; j < power.length; j++) {
                if (i == j) {
                    sum = sum + bit[i] * power[j];
                }
            }
        }
        return sum;
    }
}
